import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import bcrypt from 'bcryptjs'

// 获取用户列表
export async function GET(req: NextRequest) {
    try {
        const session = await getServerSession(authOptions)

        // 检查是否已登录
        if (!session?.user) {
            return NextResponse.json({ error: '未登录' }, { status: 401 })
        }

        // 只有教师和管理员可以查询用户列表
        if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
            return NextResponse.json({ error: '权限不足' }, { status: 403 })
        }

        // 获取查询参数
        const url = new URL(req.url)
        const roleFilter = url.searchParams.get('role')

        // 构建查询条件
        const whereClause: any = {}
        if (roleFilter) {
            whereClause.role = roleFilter
        }

        // 查询学生列表
        const students = await prisma.user.findMany({
            where: {
                role: 'STUDENT'
            },
            select: {
                id: true,
                name: true,
                email: true
            },
            orderBy: {
                name: 'asc'
            }
        })

        return NextResponse.json(students)
    } catch (error) {
        console.error('获取用户列表失败:', error)
        return NextResponse.json(
            { error: '获取用户列表失败' },
            { status: 500 }
        )
    }
}